﻿using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace RFID_code_demo
{
    class Client
    {
        #region//屬性
        Thread mythread;
        public Socket socket = null;//
        bool bExit = false;
        public bool bStopSend = false;
        public event EventHandler<EventArgs> SysHintEvent;
        EventArgs ea = new EventArgs();
        #endregion

        /// <summary>
        /// 构造
        /// </summary>
        public Client()
        {

        }

        /// <summary>
        /// 连接server
        /// </summary>
        /// <param name="connectServer"></param>
        /// <param name="clientPortNum"></param>
        /// <returns></returns>
        public bool ConnectServer(string connectServer, int clientPortNum)
        {

            bExit = false;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress serverIp = IPAddress.Parse(connectServer);
            int serverPort = clientPortNum;
            IPEndPoint iep = new IPEndPoint(serverIp, serverPort);
            IAsyncResult result = socket.BeginConnect(serverIp, serverPort, null, null);
            bool success = result.AsyncWaitHandle.WaitOne(1000, true);
            if (success == true)
            {
                mythread = new Thread(new ThreadStart(Rec));
                mythread.IsBackground = true;
                mythread.Start();
                return true;
            }
            else { return false; }



        }

        /// <summary>
        /// 断开server
        /// </summary>
        public bool Disconnect()
        {
            bExit = false;
            try
            {
                if (socket != null)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    bExit = true;
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
                bExit = false;
            }
            try
            {
                if (mythread != null)
                {
                    if (mythread.IsAlive)
                    {
                        mythread.Abort();
                        mythread = null;
                        bExit = true;
                    }
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
                bExit = false;
            }
            return bExit;
        }

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        public bool BeginSend(byte[] buff)
        {
            try
            {
                socket.Send(buff);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
            return true;
        }

        /// <summary>
        /// 接受socket thread
        /// </summary>
        public void Rec()
        {
            while (true)//(!bExit)
            {
                byte[] byteMessage = new byte[51200];
                try
                {
                    int rec = socket.Receive(byteMessage);
                    if (rec > 0)
                    {
                        if (bStopSend)
                        {
                            bStopSend = false;
                        }
                        string strresult = ASCIIEncoding.ASCII.GetString(byteMessage);
                        //MessageEvent(this, new MessageEventArgs(info));

                        SysHintEvent(strresult, ea);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        /// <summary>
        /// 检测状态
        /// </summary>
        /// <returns></returns>
        public bool IsConnected()
        {
            bool bConnectFlag = false;
            bool bLockingState = false;
            try
            {
                bLockingState = socket.Blocking;
                byte[] temp = new byte[1];
                socket.Blocking = false;
                socket.Send(temp, 0, SocketFlags.None);
                bConnectFlag = true;
            }
            catch (SocketException ex)
            {
                if (ex.NativeErrorCode.Equals(10035))
                {
                    bConnectFlag = true;
                }
                else
                {
                    bConnectFlag = false;
                }
            }
            catch
            {
                bConnectFlag = false;
            }
            finally
            {
                try
                {
                    socket.Blocking = bLockingState;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            return bConnectFlag;
        }
    }
}
